{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "IP started\n",
      "Real Part RMSE:  30.639813559 Imaginary Part RMSE: 23.5724984929\n",
      "FAIL\n",
      "CPU Utilization = [1.5, 27.8]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "from pynq import Overlay\n",
    "import asyncio\n",
    "from psutil import cpu_percent\n",
    "import numpy as np\n",
    "from pynq import Xlnk\n",
    "from pynq.lib import dma\n",
    "from scipy.linalg import dft\n",
    "import matplotlib.pyplot as plt\n",
    "import time\n",
    "\n",
    "ol = Overlay(\"interrupt.bit\")\n",
    "ol.download()\n",
    "# IP's addresses\n",
    "IP_CTRL = 0x00\n",
    "AP_START = 0x1\n",
    "GIER = 0x04\n",
    "IP_IER = 0x08\n",
    "IP_ISR = 0x0C\n",
    "INTRPT_AP_DONE = 0x1\n",
    "INTRPT_AP_READY = 0x2\n",
    "OUT_REG = 0x10\n",
    "INP_REG = 0x18\n",
    "\n",
    "_INTRPT = INTRPT_AP_DONE\n",
    "\n",
    "fact_ip = ol.fft_0\n",
    "fact_ip.write(GIER, 0x1)\n",
    "fact_ip.write(IP_IER, _INTRPT)\n",
    "\n",
    "NUM_SAMPLES = 2048\n",
    "real_error=np.zeros(NUM_SAMPLES)\n",
    "imag_error=np.zeros(NUM_SAMPLES)\n",
    "ind=np.arange(NUM_SAMPLES)\n",
    "real_rmse=np.zeros(NUM_SAMPLES)\n",
    "imag_rmse=np.zeros(NUM_SAMPLES)\n",
    "xlnk = Xlnk()\n",
    "in_r = xlnk.cma_array(shape=(NUM_SAMPLES,), dtype=np.float32) \n",
    "in_i = xlnk.cma_array(shape=(NUM_SAMPLES,), dtype=np.float32)           \n",
    "out_r = xlnk.cma_array(shape=(NUM_SAMPLES,), dtype=np.float32) \n",
    "out_i = xlnk.cma_array(shape=(NUM_SAMPLES,), dtype=np.float32)\n",
    "a = [i for i in range(NUM_SAMPLES)]\n",
    "a=np.cos(a)\n",
    "real=a.real                # Change input real and imaginary value here\n",
    "img=a.imag\n",
    "np.copyto(in_r, real)\n",
    "np.copyto(in_i, img)\n",
    "\n",
    "# Coroutine that waits for an IP to be done.\n",
    "async def read_ip(ip):\n",
    "    while True:\n",
    "        # Wait for the IP to finish.\n",
    "        await ip.interrupt.wait()\n",
    "        # Clear the interrupt and then print output's value.\n",
    "        if (ip.read(IP_ISR) & _INTRPT):\n",
    "            ip.write(IP_ISR, _INTRPT)\n",
    "            golden_op=np.fft.fft(a)\n",
    "            for i in range(NUM_SAMPLES):\n",
    "                real_error[i]=\"{0:.6f}\".format(abs(out_r[i]-golden_op.real[i]))\n",
    "                imag_error[i]=\"{0:.6f}\".format(abs(out_i[i]-golden_op.imag[i]))\n",
    "            sum_sq_real=0\n",
    "            sum_sq_imag=0\n",
    "            for i in range(NUM_SAMPLES):\n",
    "                sum_sq_real =sum_sq_real+(real_error[i]*real_error[i])\n",
    "                real_rmse = np.sqrt(sum_sq_real / (i+1))\n",
    "                sum_sq_imag =sum_sq_imag+(imag_error[i]*imag_error[i])\n",
    "                imag_rmse = np.sqrt(sum_sq_imag / (i+1))\n",
    "            print(\"Real Part RMSE: \", real_rmse, \"Imaginary Part RMSE:\", imag_rmse)    \n",
    "            if real_rmse<0.001 and imag_rmse<0.001:\n",
    "                print(\"PASS\")\n",
    "            else:\n",
    "                print(\"FAIL\")\n",
    "\n",
    "# Task for IP using the coroutine\n",
    "ip_task = asyncio.ensure_future(read_ip(fact_ip))\n",
    "\n",
    "# Coroutine for writing input and starting the IP with delay\n",
    "async def write_wait(interval):\n",
    "    await asyncio.sleep(interval)\n",
    "    \n",
    "    # write to input\n",
    "    fact_ip.write(0x30, NUM_SAMPLES)\n",
    "    fact_ip.write(0x10,in_r.physical_address)\n",
    "    fact_ip.write(0x18,in_i.physical_address)\n",
    "    fact_ip.write(0x20,out_r.physical_address)\n",
    "    fact_ip.write(0x28,out_i.physical_address)\n",
    "    \n",
    "    fact_ip.write(IP_CTRL, AP_START) # You can comment it out to test the interrupt\n",
    "    print(\"IP started\")\n",
    "    await asyncio.sleep(interval)\n",
    "\n",
    "# Run the event loop until the time interval expires\n",
    "time_interval = 2  # time in seconds\n",
    "loop = asyncio.get_event_loop()\n",
    "write_task = asyncio.ensure_future(write_wait(time_interval))\n",
    "\n",
    "# Using psutil to record CPU utilization.\n",
    "cpu_percent(percpu=True)  # Initializing the CPU monitoring.\n",
    "loop.run_until_complete(write_task)\n",
    "cpu_used = cpu_percent(percpu=True)\n",
    "\n",
    "# Printing the CPU utilization\n",
    "print('CPU Utilization = {cpu_used}'.format(**locals()))\n",
    "\n",
    "# Removing the IP task from the event loop.\n",
    "ip_task.cancel()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
